package org.easy.tool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.easy.tool.common.*;
import org.easy.tool.entity.Knowledge;
import org.easy.tool.entity.UserTrain;
import org.easy.tool.mapper.FileRecordMapper;
import org.easy.tool.mapper.KnowledgeMapper;
import org.easy.tool.mapper.UserTrainMapper;
import org.easy.tool.service.IKnowledge;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 标签服务实现类
 *
 * @author Valley
 * @since 2024-09-04 22:51:14
 */
@Service
public class KnowledgeService extends ServiceImpl<KnowledgeMapper, Knowledge> implements IKnowledge {


    @Autowired
    KnowledgeMapper knowledgeMapper;

    @Autowired
    FileRecordMapper fileRecordMapper;

    @Autowired
    UserTrainMapper userTrainMapper;

    @Override
    public LinkedHashMap submitKnowledge(LinkedHashMap data) throws Exception {
        LinkedHashMap res = new LinkedHashMap();
        Knowledge knowledge = new Knowledge();
        String pid = data.get("pid") == null ? "" : (String) data.get("pid");
        if (StringUtil.isBlank(pid)) {
            pid = "root";
        }
        //禁止前端创建用户相关标签
        if ("user".equals(pid)) return res;
        String name = (String) data.get("knowledge");
        List<Knowledge> knowledgeListByPid = knowledgeMapper.getKnowledgeListByPid(pid);
        int max = 0;
        for (Knowledge checkKnowledge : knowledgeListByPid) {
            if (checkKnowledge.getName().equals(name)) {
                res.put("status", false);
                res.put("msg", "知识点不允许重名");
                return res;
            }
            if (max < checkKnowledge.getSort()) {
                max = checkKnowledge.getSort();
            }
        }
        knowledge.setSort(max + 1);
        knowledge.setPid(pid + "");
        knowledge.setName(name);
        String color = (String) data.get("color");
        knowledge.setColor(color);
        knowledge.setCreateTime(TimeUtil.nowMS());
        knowledge.setUpdateTime(TimeUtil.nowMS());
        boolean save = save(knowledge);
        LogUtil.info("创建知识点成功", save, knowledge);
        res.put("status", true);
        return res;
    }

    public List<Knowledge> getKnowledgeChildren(String pid) {
        LambdaQueryWrapper<Knowledge> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Knowledge::getPid, pid);
        return list(wrapper);
    }

    @Override
    public List<Knowledge> getKnowledgeList(LinkedHashMap data) {
        Object idList = data.get("idList");
        List<Knowledge> list = new ArrayList<>();
        if (idList != null) {
            List<String> ids = (List<String>) idList;
            //为了保证顺序一致，不使用批量id查询，而是逐个查询，最后结果跟id顺序一致
            for (String id : ids) {
                list.add(getById(id));
            }
        } else {
            list = list();
            sortKnowledgeList(list);
        }
        return list;
    }

    @Override
    public Knowledge getKnowledgeByName(String name) {
        LambdaQueryWrapper<Knowledge> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Knowledge::getName, name);
        return getOne(wrapper);
    }

    public void sortKnowledgeList(List<Knowledge> sortList) {
        sortList.sort(Comparator.comparingInt(Knowledge::getSort));
    }

    @Override
    public Object getKnowledgeByPid(LinkedHashMap data) {
        String pid = (String) data.get("pid");
        return getKnowledgeListByPid(pid);
    }

    @Override
    public List<Knowledge> getKnowledgeListByPid(String pid) {
        List<Knowledge> knowledgeListByPid = knowledgeMapper.getKnowledgeListByPid(pid);
        sortKnowledgeList(knowledgeListByPid);
        return knowledgeListByPid;
    }

    @Override
    public List<String> getKnowledgeIdListByPid(String pid) {
        return getKnowledgeListByPid(pid).stream()
                .map(Knowledge::getId).collect(Collectors.toList());
    }


    @Override
    public Object sortKnowledge(LinkedHashMap data) {
        List<String> idList = (List<String>) data.get("idList");
        for (int i = 0; i < idList.size(); i++) {
            Knowledge knowledge = knowledgeMapper.selectById(idList.get(i));
            knowledge.setSort(i + 1);
            updateById(knowledge);
        }
        return true;
    }

    @Override
    public Object getKnowledgeById(LinkedHashMap data) {
        String id = (String) data.get("id");
        return getById(id);
    }

    @Override
    public Object updateKnowledge(LinkedHashMap data) {
        String id = (String) data.get("id");
        Knowledge knowledge = getById(id);
        Object pid = data.get("pid");
        if (StringUtil.isBlank(pid)) {
            knowledge.setPid("root");
        } else {
            knowledge.setPid(pid + "");
        }
        knowledge.setColor((String) data.get("color"));
        knowledge.setName((String) data.get("name"));
        updateById(knowledge);
        return true;
    }

    /**
     * 功能：根据id获取所有的孩子信息
     */
    public void getAllChildrenById(String id, List<Knowledge> children) {
        List<Knowledge> knowledgeList = knowledgeMapper.getKnowledgeListByPid(id);
        children.addAll(knowledgeList);
        for (Knowledge knowledge : knowledgeList) {
            getAllChildrenById(knowledge.getId(), children);
        }
    }

    public List<String> getAllKnowledgeId(String id) {
        List<Knowledge> children = new ArrayList<>();
        getAllChildrenById(id, children);
        List<String> collect = children.stream().map(Knowledge::getId).collect(Collectors.toList());
        collect.add(id);
        return collect;
    }

    @Override
    public Object deleteKnowledge(LinkedHashMap data) {
        String id = (String) data.get("id");
        List<String> allDeleted = getAllKnowledgeId(id);
        for (String deletedId : allDeleted) {
            removeById(deletedId);
        }
        return true;
    }

    @Override
    public Object hideKnowledge(LinkedHashMap data) {
        String id = (String) data.get("id");
        Knowledge knowledge = getById(id);
        knowledge.setDeleted(1);
        updateById(knowledge);
        return true;
    }

    @Override
    public Object restoreKnowledge(LinkedHashMap data) {
        String id = (String) data.get("id");
        Knowledge knowledge = getById(id);
        knowledge.setDeleted(1);
        updateById(knowledge);
        return true;
    }

    @Override
    public Object getKnowledgeNameList(LinkedHashMap data) {
        List<String> idList = (List<String>) data.get("idList");
        List<String> nameList = new ArrayList<>();
        for (String id : idList) {
            String name = getById(id).getName();
            nameList.add(name);
        }
        return nameList;
    }


    /**
     * 删除某个知识点的训练记录
     */
    private void deleteKnowledgeTrain(String id) {
        LambdaQueryWrapper<UserTrain> userTrainWrapper = new LambdaQueryWrapper<>();
        userTrainWrapper.eq(UserTrain::getTrainType, "knowledge").eq(UserTrain::getTrainId, id);
        userTrainMapper.delete(userTrainWrapper);
    }

}
